package middleware

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

func TokenAuthMiddleware(headerKey, userIDKey, signKey string) func(*gin.Context) {
	if headerKey == "" {
		headerKey = "access_token"
	}
	if userIDKey == "" {
		userIDKey = "userID"
	}
	return func(c *gin.Context) {
		token := c.Request.Header.Get(headerKey)
		c.Set(headerKey, token)
		userID, err := ParseAndValidToken([]byte(signKey), token)
		if err != nil {
			c.Error(err) // nolint: errcheck
			c.Abort()
			return
		}
		c.Set(userIDKey, userID)
		c.Next()
	}
}

func ParseAndValidToken(key []byte, token string) (string, error) {
	getKeyFun := func(*jwt.Token) (interface{}, error) {
		return key, nil
	}
	claims := new(jwt.StandardClaims)

	_, err := jwt.ParseWithClaims(token, claims, getKeyFun)
	return claims.Id, err
}
